﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Collections;

namespace JBeamLibrary.Tools
{
    public static class JValueExtension
    {
        public static byte ToByte(this JValue jValue)
        {
            byte ret;
            return byte.TryParse(jValue.ToString(CultureInfo.CurrentUICulture), out ret) ? ret : (byte)0;
        }

        public static int ToInt(this JValue jValue)
        {
            if (jValue.Value.Equals("FLT_MAX")) return int.MaxValue;
            int ret;
            return int.TryParse(jValue.ToString(CultureInfo.CurrentUICulture), out ret) ? ret : 0;
        }

        public static float ToFloat(this JValue jValue)
        {
            if (jValue.Value.Equals("FLT_MAX")) return float.MaxValue;
            float ret;
            return float.TryParse(jValue.ToString(CultureInfo.CurrentUICulture), out ret) ? ret : 0;
        }

        public static long ToLong(this JValue jValue)
        {
            if (jValue.Value.Equals("FLT_MAX")) return long.MaxValue;
            long ret;
            return long.TryParse(jValue.ToString(CultureInfo.CurrentUICulture), out ret) ? ret : 0;
        }

        public static bool ToBool(this JValue jValue)
        {
            bool ret;
            return bool.TryParse(jValue.ToString(CultureInfo.CurrentUICulture), out ret) && ret;
        }

        public static object ToListVal(this JValue jValue, IDictionary list)
        {
            var args = list.GetType().GetGenericArguments();
            var valType = args[1];

            if (valType == typeof(int))
                return jValue.ToInt();
            if (valType == typeof(float))
                return jValue.ToFloat();
            if (valType == typeof(long))
                return jValue.ToLong();
            if (valType == typeof(bool))
                return jValue.ToBool();
            if (valType == typeof(string))
                return jValue.ToString(CultureInfo.CurrentUICulture);
            return jValue;
        }
    }
}
